#encoding:utf-8

from django.http import HttpResponse,HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from login.models import Register
from groups.models import Group
from users.models import Info,Follow_user
from application.models import Invite
from django.utils import timezone
from email.mime.text import MIMEText
import re,md5,smtplib,base64,os,time

def index(request):
	return render(request,'login/login.html')

#登入
def login(request):
	try:
		email=request.GET['email2']
		#密码进行MD5加密
		pwd=md5.new(request.GET['password2']).hexdigest()
		#match=re.search(r"([+-.?$%()<>].*)",user_account)
		#if match:
		#	return HttpResponse('Your account was illegal !')
		#if re.match(r"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",user_account):
		user=Register.objects.get(email=email)
		#验证成功，将用户的部分信息放入session以便以后使用
		if pwd==user.password:
			request.session['email']=email
			request.session['id']=user.id
			info=Info.objects.get(user_id=user.id)
			request.session['name']=info.user_name
			request.session['status']=info.status
			return HttpResponse(user.id)
		else:
			return HttpResponse('密码错误 !')
		#else:
		#	user=Register.objects.get(account=user_account)
		#	if user_password==user.password:
		#		request.session['user']=user_account
		#		return HttpResponse('You are login !')
		#	else:
		#		return HttpResponse('密码错误 !')
	except:
		return HttpResponse('用户不存在!')

#注册
def register(request):
	#try:
		#account=request.GET['account']
		email=request.GET['email']
		#match=re.search(r"([+-.?*#/$%()<>].*)",account)
		#if len(account)<4:
		#	return HttpResponse('用户名过短!')
		#if match:
		#	return HttpResponse('非法的用户名 !')
		if Register.objects.filter(email=email):
			return HttpResponse('邮箱已注册!')
		else:
			password=md5.new(request.GET['password']).hexdigest()
			#邮箱的格式验证，正确则写入信息直接登入
			if re.match(r"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",email):
				s=Register(password=password,email=email)
				s.save()
				mail(email)
				i=Info(user_id=s.id,user_name=request.GET['name'],img='default.png',domain="http://mzhead.qiniudn.com",sign="这家伙很懒，什么都没写。",introduce="这家伙很懒，什么都没写。",status=0)
				Follow_user(user_id=s.id,follow_user_id=s.id).save()
				i.save()
				#return render(request,'login/home.html',{'email':email,'status':0})
				request.session['email']=email
				request.session['id']=s.id
				request.session['status']=i.status
				request.session['name']=request.GET['name']
				return HttpResponse(s.id)
			else:
				return HttpResponse('邮箱格式不正确!')
	#except:
		#account=request.GET['account'].encode("utf-8")
	#	return HttpResponse("服务器崩溃 !")

#申请内测资格
def invite(request):
	#try:
		#account=request.GET['account']
		email=request.GET['email']
		#match=re.search(r"([+-.?*#/$%()<>].*)",account)
		#if len(account)<4:
		#	return HttpResponse('用户名过短!')
		#if match:
		#	return HttpResponse('非法的用户名 !')
		password=md5.new(request.GET['password']).hexdigest()
		if re.match(r"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",email):
			s=Invite(email=request.GET['email'],password=password,age=request.GET['age'],work=request.GET['work'],position=request.GET['position'],sex=request.GET['sex'])
			s.save()
			#i=Info(user_id=s.id,user_name=request.GET['name'],img='default.png',domain="http://mzhead.qiniudn.com",sign="这家伙很懒，什么都没写。",introduce="这家伙很懒，什么都没写。",status=1)
			#Follow_user(user_id=s.id,follow_user_id=s.id).save()
			#i.save()
			#return render(request,'login/home.html',{'email':email,'status':0})
			#request.session['email']=email
			#request.session['id']=s.id
			#request.session['status']=i.status
			#request.session['name']=request.GET['name']
			return HttpResponse(s.id)
		else:
			return HttpResponse('邮箱格式不正确!')
	#except:
		#account=request.GET['account'].encode("utf-8")
	#	return HttpResponse("服务器崩溃 !")

#注册后邮箱身份验证
def verification(request):
	try:
		key=request.GET['key']
		email=base64.decodestring(key)
		user=Register.objects.get(email=email)
		info=Info.objects.get(user_id=user.id)
		info.status=1
		request.session['status']=info.status
		info.save()
		ver="邮箱通过验证"
		return render(request,"users/setting.html",{"ver":ver,'info':info})
		#return render(request,'login/home.html',{'email':email,'status':"邮箱通过验证"})
	except:
		return HttpResponse(' 服务器崩溃 !')

#注册之后的小组推荐
def addmajor(request):
	if 'u' in request.GET:
		user='mzclub'+str(request.GET['u'])
		md5u=md5.new(user).hexdigest()
		if str(md5u)==str(request.GET['token']):
			info=Info.objects.get(user_id=request.GET['u'])
			request.session['id']=request.GET['u']
			request.session['name']=info.user_name
			request.session['status']=info.status
		else:
			return HttpResponse('禁止非法操作！！')
	group=Group.objects.all().order_by('-crew_con')[0:26]
	groups=[]
	for i in group :
		if int(i.user_id) == int(request.session['id']) :
			pass
		else :
			groups.append(i)
	return render(request,'login/add.html',{'name':request.session['name'],'group1':groups[0:5],'group2':groups[6:11],'group3':groups[12:17],'group4':groups[18:23]})

#注册之后的用户推荐
def adduser(request):
	user=Info.objects.all().order_by('?')[0:26]
	users=[]
	for i in user:
		if int(i.user_id) == int(request.session['id']) :
			pass
		else :
			users.append(i)
	return render(request,'login/user.html',{'name':request.session['name'],'user1':users[0:5],'user2':users[6:11],'user3':users[12:17],'user4':users[18:23]})

#Python的邮箱类
def mail(address):
	mailto_list=address
	#邮箱的服务器
	mail_host="smtp.exmail.qq.com"
	#发送者的名字
	mail_name="麦知网"
	#发送者的邮箱
	mail_user="service@mazclub.com"
	#邮箱密码
	mail_pass="maizhi123"
	#邮箱
	mail_postfix="mazclub.com"
	#发送者
	me=mail_name+"<"+mail_user+"@"+mail_postfix+">"
	#发送内容，html格式
	msg = MIMEText('<html><h1>您好：</h1>欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识<br/>也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!<br/>在这里您将体验：<br/><b>小组:</b>找到志趣相投者，不亦乐乎。<br/><b>课程:</b>发现有价值的知识，不亦快乎。<br/><b>悬赏:</b>三人行，必有我师，坦诚相待，不亦君子乎。<br/>更多乐趣请到  www.mazclub.com<br/>祝您学习愉快！<br/><hr/>/verification/?key='+base64.encodestring(address)+'<hr/><br/>麦知网服务团队<br/>客户问题建议反馈 ： feedback@mazclub.com<br/>企业战略合作联系 ： cooperation@mazclub.com<br/></html>','html','utf-8')
	#content="/verification/?key="+base64.encodestring(address)+"\n您好：\n欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识\n也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!\n在这里您将体验：\n小组:找到志趣相投者，不亦乐乎。\n课程:发现有价值的知识，不亦快乎。\n悬赏:三人行，必有我师，坦诚相待，不亦君子乎。\n更多乐趣请到  www.mazclub.com\n祝您学习愉快！\n麦知网服务团队\n客户问题建议反馈 ： feedback@mazclub.com\n企业战略合作联系 ： cooperation@mazclub.com\n"
	#msg = MIMEText(content)
	#主题
	msg['Subject'] = '麦知网确认邮件!'
	#来自
	msg['From'] = me
	#发往
	msg['To'] = mailto_list
	try:
	    s = smtplib.SMTP()
	    s.connect(mail_host)
	    s.login(mail_user,mail_pass)
	    s.sendmail(me, mailto_list, msg.as_string())
	    s.quit()
	    return 'OK !'
	except Exception, e:
	    #print str(e)
	    return 'False !'

#检验邮箱是否注册与是否已经申请
def check(request):
	if int(request.GET['method']) == 1 :
		email=Register.objects.filter(email=str(request.GET['parameter']))
		if email :
			return HttpResponse(2)
		else:
			return HttpResponse(1)
	elif int(request.GET['method']) == 2 :
		if Invite.objects.filter(email=request.GET['parameter']):
			return HttpResponse(2)
		else:
			return HttpResponse(1)

#找回密码
def findpwd(request):
	"""
	加密与解密方式
	encode=timestamp+id*2-50
	decode:id=(encode+50-timestamp)/2
	"""
	try:
		emailOri=Register.objects.get(email=request.GET['email'])
		timestamp=int(time.time())
		#email=base64.encodestring(emailOri.email)
		#timestamp=base64.encodestring(str(timestamp))
		user_id=emailOri.id
		parameter=timestamp+int(user_id)*2-50
		#parameter=parameter.replace(' ','')

		#发送邮件
		url='/register/pwd/?token='+str(parameter)+"&email="+str(emailOri.email)+"&time="+str(timestamp)
		mailto_list=request.GET['email']
		mail_host="smtp.exmail.qq.com"
		mail_name="麦知网"
		mail_user="service@mazclub.com"
		mail_pass="maizhi123"
		mail_postfix="mazclub.com"
		me=mail_name+"<"+mail_user+"@"+mail_postfix+">"
		msg = MIMEText('<html><h1>您好：</h1>请点击下面的链接来修改您的密码，本链接一个小时内有效！<a href='+url+'>点击这里</a><br>企业战略合作联系 ： cooperation@mazclub.com<br/></html>','html','utf-8')
		#content="/verification/?key="+base64.encodestring(address)+"\n您好：\n欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识\n也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!\n在这里您将体验：\n小组:找到志趣相投者，不亦乐乎。\n课程:发现有价值的知识，不亦快乎。\n悬赏:三人行，必有我师，坦诚相待，不亦君子乎。\n更多乐趣请到  www.mazclub.com\n祝您学习愉快！\n麦知网服务团队\n客户问题建议反馈 ： feedback@mazclub.com\n企业战略合作联系 ： cooperation@mazclub.com\n"
		#msg = MIMEText(content)
		msg['Subject'] = '麦知网修改密码邮件!'
		msg['From'] = me
		msg['To'] = mailto_list
		try:
		    s = smtplib.SMTP()
		    s.connect(mail_host)
		    s.login(mail_user,mail_pass)
		    s.sendmail(me, mailto_list, msg.as_string())
		    s.quit()
		    return HttpResponse(1)
		except Exception, e:
		    #print str(e)
		    return HttpResponse(2)
	except:
		return HttpResponse(3)

#找回密码的数据库操作
def pwd(request):
	send=request.GET['time']
	user_id=(int(request.GET['token'])+50-int(send))/2
	now=int(time.time())
	#URL的生存时间为1小时
	if int(now)-int(send)>3600:
		return HttpResponse("链接超时！请重新申请")
	else :
		return render(request,'login/pwd.html',{'email':request.GET['email'],'id':user_id})
	#return HttpResponse(email+str('--')+time+str('--')+user)

#更新密码
def newpwd(request):
	user=Register.objects.get(id=request.POST['id'])
	if user.email != request.POST['email']:
		return HttpResponse("您的用户资料不匹配！")
	else :
		user.password=md5.new(request.POST['pwd']).hexdigest()
		user.save()
	return HttpResponseRedirect("http://192.168.1.120:8866")